from redis import Redis
from config import REDIS_IP, REDIS_PORT
import pickle


# 通过调整huey task在redis队列中的顺序，实现调整huey task优先级
def redis_queue_change(task_ids: list):

    r = Redis(host=REDIS_IP, port=REDIS_PORT, db=0)

    # keys = r.keys()
    # print(keys)  # 获取redis队列keys, 输出结果: [b'huey.redis.app', b'huey.results.app']
    queue_name = 'huey.redis.app'

    # 获取队列长度
    length = r.llen(queue_name)

    all_tasks = []
    for i in range(length):
        queue_task = r.rpop(queue_name)
        all_tasks.append(queue_task)

    # 调整优先级, 如果传过来的task_id不在all_tasks, 不存入all_after
    all_after = []
    for task_id in task_ids:
        for item in all_tasks:
            if task_id in pickle.loads(item):
                all_after.append(item)
                break

    # 按调整好的顺序传入redis队列
    for item in all_after:
        r.lpush(queue_name, item)